package com.example.rwq_test.niuke.list;

/**
 * @Description: 反转链表
 *  给定一个单链表的头结点pHead(该头节点是有值的，比如在下图，它的val是1)，长度为n，反转该链表后，返回新链表的表头。
 *  如当输入链表{1,2,3}时，经反转后，原链表变为{3,2,1}，所以对应的输出为{3,2,1}。
 *
 * @Author：dingdang4D
 * @Date：2024/6/4
 */
public class ReverseList {

    public static ListNode reverseList (ListNode head) {
        // write code here
        if (head == null) {
            return null;
        }
        ListNode pre = null;
        ListNode cur = head;

        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode dummy = new ListNode(-1);
        ListNode head = new ListNode(1);
        dummy.next = head;
        for (int i = 2; i < 12; i++) {
            ListNode listNode = new ListNode(i);
            head.next = listNode;
            head = head.next;
        }

        ListNode listNode = reverseList(dummy.next);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}
